"use client";
import {
  Dispatch,
  ForwardedRef,
  forwardRef,
  Fragment,
  ReactNode,
  SetStateAction,
  useImperativeHandle,
  useOptimistic,
  useRef,
} from "react";
interface Props {
  children: ReactNode;
  setToPageId: Dispatch<SetStateAction<string>>;
}

interface Handle {
  focusAddComment: () => void;
}

export default forwardRef(
  ({ children, setToPageId }: Props, inputRef: ForwardedRef<Handle>) => {
    const [isChinkApiL, setIsChinkApiL] = useOptimistic(
      false,
      (state, value: boolean) => value
    );

    const formAction = async () => {
      setIsChinkApiL(true);
      await fetch(`/af/api/opt`);
    };

    const addCommentRef = useRef<HTMLInputElement>(null);

    useImperativeHandle(
      inputRef,
      () => ({
        focusAddComment() {
          addCommentRef?.current?.focus();
        },
      }),
      []
    );

    return (
      <Fragment>
        <div>
          {isChinkApiL && <p>提交完成</p>}
          {/* 输入框的Ref不能是父组件传进来的 */}
          <input
            ref={addCommentRef}
            onChange={(e) => setToPageId(e.target.value)}
          ></input>
        </div>
        <div>{children}</div>
        <div>
          <form action={formAction}>
            <button type="submit">opt</button>
          </form>
        </div>
      </Fragment>
    );
  }
);
